// 页面加载完成后执行初始化
document.addEventListener('DOMContentLoaded', () => {
    // 检查登录状态和身份
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    if (!userInfo || userInfo.utype !== 0) {
        window.location.href = '../login.html';
        return;
    }

    // 初始化页面
    initPage();

    // 添加导航事件监听
    document.querySelectorAll('.menu-item').forEach(item => {
        item.addEventListener('click', (e) => {
            e.preventDefault();
            const page = e.target.dataset.page;
            
            // 更新导航状态
            document.querySelectorAll('.menu-item').forEach(i => i.classList.remove('active'));
            e.target.classList.add('active');
            
            // 更新页面标题和按钮
            updatePageHeader(page);
            
            // 加载对应内容
            switch(page) {
                case 'users':
                    loadUsers();
                    break;
                case 'announcements':
                    loadMessages(0);
                    break;
                case 'notices':
                    loadMessages(1);
                    break;
                case 'news':
                    loadMessages(2);
                    break;
                case 'comments':
                    loadComments();
                    break;
            }
        });
    });

    // 添加按钮事件监听
    const addButton = document.getElementById('addButton');
    if (addButton) {
        addButton.addEventListener('click', () => {
            const activePage = document.querySelector('.menu-item.active').dataset.page;
            switch(activePage) {
                case 'users':
                    showAddUserModal();
                    break;
                case 'announcements':
                    showAddMessageModal(0);
                    break;
                case 'notices':
                    showAddMessageModal(1);
                    break;
                case 'news':
                    showAddMessageModal(2);
                    break;
            }
        });
    }

    // 添加搜索功能
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('input', handleSearch);
    }

    // 更新用户信息显示
    updateUserInfo();
});

// 更新用户信息显示
function updateUserInfo() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    const userInfoElement = document.getElementById('userInfo');
    if (userInfoElement && userInfo) {
        userInfoElement.innerHTML = `
            <span>管理员：${userInfo.uid}</span>
            <a href="javascript:void(0)" onclick="handleLogout()">退出</a>
        `;
    }
}

// 处理退出登录
function handleLogout() {
    localStorage.removeItem('userInfo');
    window.location.href = '../login.html';
}

// 处理搜索功能
function handleSearch(e) {
    const searchText = e.target.value.toLowerCase();
    const activePage = document.querySelector('.menu-item.active').dataset.page;
    const rows = document.querySelectorAll('.table tbody tr');

    rows.forEach(row => {
        let searchContent = '';
        switch(activePage) {
            case 'users':
                searchContent = row.querySelector('td:first-child').textContent; // 搜索用户账号
                break;
            case 'announcements':
            case 'notices':
            case 'news':
                searchContent = row.querySelector('td:first-child').textContent + 
                              row.querySelector('td:nth-child(2)').textContent; // 搜索标题和内容
                break;
            case 'comments':
                searchContent = row.querySelector('td:nth-child(2)').textContent + 
                              row.querySelector('td:nth-child(3)').textContent; // 搜索用户和评论内容
                break;
        }
        row.style.display = searchContent.toLowerCase().includes(searchText) ? '' : 'none';
    });
}

// 初始化页面
function initPage() {
    // 加载默认页面（用户列表）
    loadUsers();
    
    // 更新添加按钮显示状态
    const addButton = document.getElementById('addButton');
    if (addButton) {
        const activePage = document.querySelector('.menu-item.active').dataset.page;
        addButton.style.display = activePage === 'comments' ? 'none' : 'block';
    }
}

// 处理文件上传
async function handleFileUpload(file, mid) {
    try {
        // 获取文件类型
        const kind = file.name.split('.').pop().toLowerCase();
        const base64Data = await FileUtils.encodeFile(file);
        await API.message.uploadFile({
            filedata: base64Data,
            mid: mid,
            kind: kind // 添加文件类型参数
        });
    } catch (error) {
        console.error('文件上传失败:', error);
        throw error;
    }
}

// 处理图片上传
async function handleImageUpload(file, mid) {
    try {
        const base64Data = await FileUtils.encodeFile(file);
        await API.message.uploadPhoto({
            photodata: base64Data,
            mid: mid
        });
    } catch (error) {
        console.error('图片上传失败:', error);
        throw error;
    }
}

// 页面配置
const PAGE_CONFIG = {
    users: {
        title: '用户管理',
        addButtonText: '添加用户',
        searchPlaceholder: '搜索用户账号...'
    },
    announcements: {
        title: '公告管理',
        addButtonText: '发布公告',
        searchPlaceholder: '搜索公告标题...'
    },
    notices: {
        title: '通知管理',
        addButtonText: '发布通知',
        searchPlaceholder: '搜索通知标题...'
    },
    news: {
        title: '新闻管理',
        addButtonText: '发布新闻',
        searchPlaceholder: '搜索新闻标题...'
    },
    comments: {
        title: '评论管理',
        addButtonText: '',
        searchPlaceholder: '搜索评论内容...'
    }
};

// 当前页面状态
let currentPage = 'users';
// 当前消息类型，使用 CONFIG 中定义的常量
let currentType = 0; // 默认为公告类型

// 更新页面标题和按钮
function updatePageHeader(page) {
    const config = PAGE_CONFIG[page];
    const pageTitle = document.getElementById('pageTitle');
    const addButton = document.getElementById('addButton');
    const searchInput = document.getElementById('searchInput');

    pageTitle.textContent = config.title;
    
    // 更新当前消息类型
    switch(page) {
        case 'announcements':
            currentType = 0; // 公告
            break;
        case 'notices':
            currentType = 1; // 通知
            break;
        case 'news':
            currentType = 2; // 新闻
            break;
    }
    
    if (config.addButtonText) {
        addButton.style.display = 'block';
        addButton.textContent = config.addButtonText;
    } else {
        addButton.style.display = 'none';
    }
    
    searchInput.placeholder = config.searchPlaceholder;
}

// 加载用户列表
async function loadUsers() {
    try {
        const response = await HttpClient.get(CONFIG.API.USER.GET_ALL);
        const contentBody = document.getElementById('contentBody');
        
        if (Array.isArray(response)) {
            contentBody.innerHTML = `
                <table class="table">
                    <thead>
                        <tr>
                            <th>账号</th>
                            <th>用户类型</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${response.map(user => `
                            <tr>
                                <td>${user.uid}</td>
                                <td>${getUserType(user.utype)}</td>
                                <td class="action-buttons">
                                    <button class="action-btn edit-btn" onclick="editUser('${user.uid}', ${user.utype})">编辑</button>
                                    <button class="action-btn delete-btn" onclick="deleteUser('${user.uid}')">删除</button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
        }
    } catch (error) {
        console.error('加载用户列表失败:', error);
    }
}

// 显示添加用户模态框
function showAddUserModal() {
    const modal = document.getElementById('modal');
    const modalTitle = document.getElementById('modalTitle');
    const modalBody = document.getElementById('modalBody');
    
    modalTitle.textContent = '添加用户';
    modalBody.innerHTML = `
        <form id="userForm" onsubmit="handleAddUser(event)">
            <div class="form-group">
                <label for="uid">账号</label>
                <input type="text" id="uid" required>
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" required>
            </div>
            <div class="form-group">
                <label for="utype">用户类型</label>
                <select id="utype" required>
                    <option value="1">员工</option>
                    <option value="2">注册用户</option>
                </select>
            </div>
            <div class="form-actions">
                <button type="submit" class="submit-btn">确认添加</button>
                <button type="button" class="cancel-btn" onclick="closeModal()">取消</button>
            </div>
        </form>
    `;
    
    modal.style.display = 'block';
}

// 处理添加用户
async function handleAddUser(event) {
    event.preventDefault();
    
    const uid = document.getElementById('uid').value;
    const password = document.getElementById('password').value;
    const utype = parseInt(document.getElementById('utype').value);
    
    try {
        await HttpClient.post(CONFIG.API.USER.ADD, {
            uid,
            password,
            utype
        });
        
        closeModal();
        loadUsers();
        alert('添加用户成功');
    } catch (error) {
        alert('添加用户失败');
        console.error('添加用户失败:', error);
    }
}

// 编辑用户
async function editUser(uid, currentUtype) {
    const modal = document.getElementById('modal');
    const modalTitle = document.getElementById('modalTitle');
    const modalBody = document.getElementById('modalBody');
    
    modalTitle.textContent = '编辑户';
    modalBody.innerHTML = `
        <form id="userForm" onsubmit="handleEditUser(event, '${uid}')">
            <div class="form-group">
                <label>账号</label>
                <input type="text" value="${uid}" disabled class="form-control">
            </div>
            <div class="form-group">
                <label for="password">新密码</label>
                <input type="password" id="password" class="form-control" placeholder="留空则不修改密码">
            </div>
            <div class="form-group">
                <label for="utype">用户类型</label>
                <select id="utype" class="form-control" required>
                    <option value="1" ${currentUtype === 1 ? 'selected' : ''}>员工</option>
                    <option value="2" ${currentUtype === 2 ? 'selected' : ''}>注册用户</option>
                </select>
            </div>
            <div class="form-actions">
                <button type="button" class="btn btn-cancel" onclick="closeModal()">取消</button>
                <button type="submit" class="btn btn-confirm">确定</button>
            </div>
        </form>
    `;
    
    modal.style.display = 'block';
}

// 处理编辑用户
async function handleEditUser(event, uid) {
    event.preventDefault();
    
    const password = document.getElementById('password').value;
    const utype = parseInt(document.getElementById('utype').value);
    
    try {
        const data = {
            uid,
            utype
        };
        
        if (password) {
            data.password = password;
        }
        
        await HttpClient.post(CONFIG.API.USER.UPDATE, data);
        
        closeModal();
        loadUsers();
        alert('修改用户成功');
    } catch (error) {
        alert('修改用户失败');
        console.error('修改用户失败:', error);
    }
}

// 删除用户
async function deleteUser(uid) {
    if (!confirm(`确定要删除用户 ${uid} 吗？`)) return;
    
    try {
        await HttpClient.post(`${CONFIG.API.USER.DELETE}/${uid}`);
        loadUsers();
        alert('删除用户成功');
    } catch (error) {
        alert('删除用户失败');
        console.error('删除用户失败:', error);
    }
}

// 格式化日期显示
function formatDate(dateStr) {
    if (!dateStr) return '';
    // 只取日期部分，不显示时间
    return dateStr.split(' ')[0];
}

// 加载消息列表
async function loadMessages(type) {
    try {
        const response = await API.message.search({
            mtype: type
        });

        const contentBody = document.getElementById('contentBody');
        
        if (Array.isArray(response)) {
            contentBody.innerHTML = `
                <table class="table">
                    <thead>
                        <tr>
                            <th>标题</th>
                            <th>内容预览</th>
                            <th>发布时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${response.map(message => `
                            <tr>
                                <td>${message.head}</td>
                                <td>${message.context.substring(0, 50)}...</td>
                                <td>${formatDate(message.mtime)}</td>
                                <td class="action-buttons">
                                    <button class="action-btn edit-btn" onclick="editMessage(${message.mid}, ${type})">编辑</button>
                                    <button class="action-btn delete-btn" onclick="deleteMessage(${message.mid})">删除</button>
                                    <button class="action-btn view-btn" onclick="viewMessage(${message.mid})">查看</button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
        }
    } catch (error) {
        console.error('加载消息列表失败:', error);
        alert('加载消息列表失败');
    }
}

// 显示添加消息模态框
function showAddMessageModal(type) {
    const modal = document.getElementById('modal');
    const modalTitle = document.getElementById('modalTitle');
    const modalBody = document.getElementById('modalBody');
    
    const titles = {
        0: '发布公告',
        1: '发布通知',
        2: '发布新闻'
    };
    
    modalTitle.textContent = titles[type];
    modalBody.innerHTML = `
        <form id="messageForm" onsubmit="handleAddMessage(event, ${type})">
            <div class="form-group">
                <label for="head">标题</label>
                <input type="text" id="head" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="context">内容</label>
                <textarea id="context" class="form-control" required rows="10"></textarea>
            </div>
            <div class="form-group">
                <label for="photos">图片（可选）</label>
                <input type="file" id="photos" class="form-control" multiple accept="image/*">
                <div id="imagePreview" class="image-preview"></div>
            </div>
            <div class="form-group">
                <label for="files">附件（可选）</label>
                <input type="file" id="files" class="form-control" multiple>
                <div id="fileList" class="file-list"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                <button type="submit" class="btn btn-primary">发布</button>
            </div>
        </form>
    `;
    
    modal.style.display = 'block';
}

// 处理添加消息
async function handleAddMessage(event, type) {
    event.preventDefault();
    
    const head = document.getElementById('head').value.trim();
    const context = document.getElementById('context').value.trim();
    
    if (!head || !context) {
        alert('标题和内容不能为空');
        return;
    }
    
    const photoFiles = document.getElementById('photos').files;
    const attachmentFiles = document.getElementById('files').files;
    
    try {
        // 1. 添加消息基本信息
        const messageResponse = await HttpClient.post(CONFIG.API.MESSAGE.ADD, {
            head,
            context,
            mtype: type
        });
        
        const mid = messageResponse; // API返回的消息ID
        
        // 2. 上传图片（如果有）
        if (photoFiles.length > 0) {
            for (let file of photoFiles) {
                await handleImageUpload(file, mid);
            }
        }
        
        // 3. 上传附件（如果有）
        if (attachmentFiles.length > 0) {
            for (let file of attachmentFiles) {
                await handleFileUpload(file, mid);
            }
        }
        
        closeModal();
        loadMessages(type);
        alert('发布成功');
    } catch (error) {
        alert('发布失败');
        console.error('发布失败:', error);
    }
}

// 编辑消息
async function editMessage(mid, type) {
    try {
        // 获取消息详情
        const response = await HttpClient.post(CONFIG.API.MESSAGE.GET_DETAIL, {
            mid: mid
        });

        const { messages, photo, file } = response;
        
        const modal = document.getElementById('modal');
        const modalTitle = document.getElementById('modalTitle');
        const modalBody = document.getElementById('modalBody');
        
        modalTitle.textContent = '编辑消息';
        modalBody.innerHTML = `
            <form id="messageForm" onsubmit="handleEditMessage(event, ${mid}, ${type})">
                <div class="form-group">
                    <label for="head">标题</label>
                    <input type="text" id="head" value="${messages.head}" required>
                </div>
                <div class="form-group">
                    <label for="context">内容</label>
                    <textarea id="context" required rows="6">${messages.context}</textarea>
                </div>
                <div class="form-group">
                    <label>当前图片</label>
                    <div class="current-images">
                        ${photo ? photo.map(p => {
                            const imageUrl = FileUtils.decodeToUrl(p.photodata);
                            return `
                                <div class="image-item">
                                    <img src="${imageUrl}" alt="图片">
                                    <button type="button" onclick="deletePhoto(${p.pid}, ${mid})">删除</button>
                                </div>
                            `;
                        }).join('') : ''}
                    </div>
                    <label for="photos">添加新图片</label>
                    <input type="file" id="photos" multiple accept="image/*">
                    <div id="imagePreview" class="image-preview"></div>
                </div>
                <div class="form-group">
                    <label>当前附件</label>
                    <div class="current-files">
                        ${file ? file.map(f => `
                            <div class="file-item">
                                <span>附件${f.fid}</span>
                                <button type="button" onclick="deleteFile(${f.fid}, ${mid})">删除</button>
                            </div>
                        `).join('') : ''}
                    </div>
                    <label for="files">添加新附件</label>
                    <input type="file" id="files" multiple>
                    <div id="fileList" class="file-list"></div>
                </div>
                <div class="form-actions">
                    <button type="submit" class="submit-btn">保存修改</button>
                    <button type="button" class="cancel-btn" onclick="closeModal()">取消</button>
                </div>
            </form>
        `;
        
        modal.style.display = 'block';
    } catch (error) {
        console.error('获取消息详情失败:', error);
        alert('获取消息详情失败');
    }
}

// 处理编辑消息
async function handleEditMessage(event, mid, type) {
    event.preventDefault();
    
    const head = document.getElementById('head').value.trim();
    const context = document.getElementById('context').value.trim();
    
    if (!head || !context) {
        alert('标题和内容不能为空');
        return;
    }
    
    const photoFiles = document.getElementById('photos').files;
    const attachmentFiles = document.getElementById('files').files;
    
    try {
        // 1. 更新消息基本信息
        await HttpClient.post(CONFIG.API.MESSAGE.UPDATE, {
            mid,
            head,
            context,
            mtype: type
        });
        
        // 2. 上传新图片（如果有）
        if (photoFiles.length > 0) {
            for (let file of photoFiles) {
                await handleImageUpload(file, mid);
            }
        }
        
        // 3. 上传新附件（如果有）
        if (attachmentFiles.length > 0) {
            for (let file of attachmentFiles) {
                await handleFileUpload(file, mid);
            }
        }
        
        closeModal();
        loadMessages(type);
        alert('修改成功');
    } catch (error) {
        alert('修改失败');
        console.error('修改失败:', error);
    }
}

// 删除消息
async function deleteMessage(mid) {
    if (!confirm('确定要删除这条消息吗？相关图片、文件和评论也会被删除。')) return;
    
    try {
        // 等待删除请求完成
        await API.message.delete(mid);
        // 等待列表刷新完成
        await loadMessages(currentType);
        alert('删除成功');
    } catch (error) {
        console.error('删除消息失败:', error);
        alert('删除失败');
    }
}

// 删除图片
async function deletePhoto(pid, mid) {
    if (!confirm('确定要删除这张图片吗？')) return;
    
    try {
        // 等待删除请求完成
        const deleteResult = await API.message.deletePhoto({
            pid: pid,
            mid: mid
        });
        
        if (deleteResult) {
            // 等待编辑框刷新完成
            try {
                await editMessage(mid, currentType);
                alert('删除图片成功');
            } catch (error) {
                console.error('刷新编辑框失败:', error);
                alert('删除成功，但刷新页面失败');
            }
        } else {
            alert('删除图片失败');
        }
    } catch (error) {
        console.error('删除图片失败:', error);
        alert('删除图片失败');
    }
}

// 删除文件
async function deleteFile(fid, mid) {
    if (!confirm('确定要删除这个文件吗？')) return;
    
    try {
        // 等待删除请求完成
        const deleteResult = await API.message.deleteFile({
            fid: fid,
            mid: mid
        });
        
        if (deleteResult) {
            // 等待编辑框刷新完成
            try {
                await editMessage(mid, currentType);
                alert('删除文件成功');
            } catch (error) {
                console.error('刷新编辑框失败:', error);
                alert('删除成功，但刷新页面失败');
            }
        } else {
            alert('删除文件失败');
        }
    } catch (error) {
        console.error('删除文件失败:', error);
        alert('删除文件失败');
    }
}

// 加载评论列表
async function loadComments() {
    try {
        const response = await HttpClient.post(CONFIG.API.COMMENT.FIND, {});
        const contentBody = document.getElementById('contentBody');
        const validComments = response.filter(comment => comment.commnet && comment.commnet.trim() !== '');
            
        if (Array.isArray(validComments)) {
            contentBody.innerHTML = `
                <table class="table">
                    <thead>
                        <tr>
                            <th>评论ID</th>
                            <th>用户账号</th>
                            <th>评论内容</th>
                            <th>所属新闻</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${validComments.map(comment => `
                            <tr>
                                <td>${comment.cid}</td>
                                <td>${comment.uid}</td>
                                <td>${comment.commnet}</td>
                                <td>
                                    <button class="action-btn view-btn" onclick="viewMessage(${comment.mid})">
                                        查看新闻
                                    </button>
                                </td>
                                <td>
                                    <button class="action-btn delete-btn" onclick="deleteComment(${comment.cid}, ${comment.mid})">
                                        删除
                                    </button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
        }
    } catch (error) {
        console.error('加载评论列表失败:', error);
    }
}

// 删除评论
async function deleteComment(cid, mid) {
    if (!confirm('确定要删除这条评论吗？')) return;
    
    try {
        await HttpClient.post(CONFIG.API.COMMENT.DELETE, {
            cid,
            mid
        });
        loadComments();
        alert('删除评论成功');
    } catch (error) {
        alert('删除评论失败');
        console.error('删除评论失败:', error);
    }
}

// 查看消息详情
async function viewMessage(mid) {
    try {
        const response = await API.message.getDetail({
            mid: mid
        });

        const { messages, photo, file } = response;
        
        const modal = document.getElementById('modal');
        const modalTitle = document.getElementById('modalTitle');
        const modalBody = document.getElementById('modalBody');
        
        modalTitle.textContent = messages.head;
        modalBody.innerHTML = `
            <div class="message-detail">
                <div class="message-meta">
                    <span>发布时间：${formatDate(messages.mtime)}</span>
                </div>
                <div class="message-content">${messages.context}</div>
                ${photo && photo.length > 0 ? `
                    <div class="message-images">
                        ${photo.map(p => {
                            const imageUrl = FileUtils.decodeToUrl(p.photodata);
                            return `
                                <img src="${imageUrl}" 
                                     alt="附图" 
                                     onclick="showFullImage('${imageUrl}')">
                            `;
                        }).join('')}
                    </div>
                ` : ''}
                ${file && file.length > 0 ? `
                    <div class="message-files">
                        <h3>附件列表</h3>
                        ${file.map(f => `
                            <div class="file-item" onclick="FileUtils.downloadFile('${f.filedata}', 'file_${f.fid}')">
                                <span class="file-icon">📄</span>
                                <span class="file-name">附件${f.fid}</span>
                            </div>
                        `).join('')}
                    </div>
                ` : ''}
            </div>
        `;
        
        modal.style.display = 'block';
    } catch (error) {
        console.error('获取消息详情失败:', error);
        alert('获取消息详情失败');
    }
}

// 图片全屏预览
function showFullImage(imageUrl) {
    const overlay = document.createElement('div');
    overlay.className = 'image-overlay';
    overlay.onclick = () => document.body.removeChild(overlay);
    
    const img = document.createElement('img');
    img.src = imageUrl;
    overlay.appendChild(img);
    document.body.appendChild(overlay);
}

// 搜索功能
function handleSearch(event) {
    const searchText = event.target.value.toLowerCase();
    const currentContent = document.querySelectorAll('.table tbody tr');
    
    currentContent.forEach(row => {
        const text = row.textContent.toLowerCase();
        row.style.display = text.includes(searchText) ? '' : 'none';
    });
}

// 关闭模态框
function closeModal() {
    const modal = document.getElementById('modal');
    modal.style.display = 'none';
}

// 获取用户类型文本
function getUserType(utype) {
    const types = {
        0: '管理员',
        1: '员工',
        2: '注册用户'
    };
    return types[utype] || '未知';
}